﻿#include "MqttWrapper.h"
#include <QDebug>
#include <QCoreApplication>

MqttWrapper::MqttWrapper(const char *id, bool cleanSession) : mosqpp::mosquittopp(id, cleanSession),m_id(id)
{
    mosqpp::lib_init();
    moveToThread(this);
}

MqttWrapper::~MqttWrapper()
{
    loop_stop(true);
    mosqpp::lib_cleanup();
}

void MqttWrapper::setAddress(const QString &url, int port)
{
    this->url = url;
    this->port = port;
}

void MqttWrapper::run()
{
    mosquittopp::connect_async(url.toUtf8().constData(), port, 10);
    int ret = loop_start();
    if(ret) {
        qDebug() << "loop start error" << ret;
        return;
    }

    exec();
}

void MqttWrapper::on_connect(int rc)
{
    qDebug() << "mqtt connected" << rc;
    emit connected();
}

void MqttWrapper::on_disconnect(int rc)
{
    static bool isFirst = true;

    qDebug() << "mqtt disconnect: "<< rc;

    /* 7:顶替，19：断网 */
    if (rc == 7) {
        qDebug() << "exit";
//        qApp->exit(0);
    }

    if (rc == 19) {
        qDebug() << "network error";
    }

    if(isFirst)
    {
        isFirst = false;

        return;
    }

    emit disconnected();
}

void MqttWrapper::on_error()
{
    qDebug() << "mqtt error";
    emit error();
}

void MqttWrapper::mqttDisconnect()
{
    mosqpp::mosquittopp::disconnect();
}

void MqttWrapper::qobjectDisconnect()
{
    QThread::disconnect();
}

void MqttWrapper::reducePublish(const char *topic, const QByteArray &data)
{
    qDebug() << "send topic" << topic;
    publish(nullptr,topic,data.size(),data.constData());
}

void MqttWrapper::on_publish(int mid)
{
    Q_UNUSED(mid);
}

void MqttWrapper::on_subscribe(int mid, int qos_count, const int *granted_qos)
{
    Q_UNUSED(mid);
    Q_UNUSED(qos_count);
    Q_UNUSED(granted_qos);
}

void MqttWrapper::on_message(const struct mosquitto_message *message)
{
    emit textMessageReceived(QString(message->topic),QByteArray((const char*)message->payload,message->payloadlen));
}

void MqttWrapper::on_log(int level, const char *str)
{
    if (level == MOSQ_LOG_ERR)
        qDebug() << str;
}

void MqttWrapper::on_unsubscribe(int mid)
{
    Q_UNUSED(mid);
}
